package com.ruoyi.system.service.impl;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.*;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.MdjfCaseBczl;
import com.ruoyi.system.domain.MdjfCasePerson;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MdjfCaseMainMapper;
import com.ruoyi.system.domain.MdjfCaseMain;
import java.time.ZoneId;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 矛盾纠纷--案件主事件Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-28
 */
@Service
public class MdjfCaseMainServiceImpl implements IMdjfCaseMainService 
{
    @Autowired
    private MdjfCaseMainMapper mdjfCaseMainMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMdjfCasePersonService mdjfCasePersonService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IMdjfCaseBczlService mdjfCaseBczlService;

    /**
     * 查询矛盾纠纷--案件主事件
     * 
     * @param caseMainId 矛盾纠纷--案件主事件主键
     * @return 矛盾纠纷--案件主事件
     */
    @Override
    public MdjfCaseMain selectMdjfCaseMainByCaseMainId(Long caseMainId)
    {
        MdjfCaseMain m = mdjfCaseMainMapper.selectMdjfCaseMainByCaseMainId(caseMainId);
        if (m != null) {
           return buildData(m);
        }
        return m;
    }

    /**
     * 查询矛盾纠纷--案件主事件列表
     * 
     * @param mdjfCaseMain 矛盾纠纷--案件主事件
     * @return 矛盾纠纷--案件主事件
     */
    @Override
    @DataScope(deptAlias = "m", userAlias = "m")
    public List<MdjfCaseMain> selectMdjfCaseMainList(MdjfCaseMain mdjfCaseMain)
    {
        List<MdjfCaseMain> mdjfCaseMainList = mdjfCaseMainMapper.selectMdjfCaseMainList(mdjfCaseMain);
        if (mdjfCaseMainList == null || mdjfCaseMainList.size() == 0) {
            return mdjfCaseMainList;
        }
        for(MdjfCaseMain m:mdjfCaseMainList){
            m = buildData(m);
        }
        return mdjfCaseMainList;
    }

    /**
     * 新增矛盾纠纷--案件主事件
     * 
     * @param mdjfCaseMain 矛盾纠纷--案件主事件
     * @return 结果
     */
    @Override
    public int insertMdjfCaseMain(MdjfCaseMain mdjfCaseMain)
    {

        Date createDate = DateUtils.getNowDate();
        mdjfCaseMain.setCreateTime(createDate);
        // 转换为 LocalDateTime 进行计算
//        LocalDateTime createTime = createDate.toInstant()
//                .atZone(ZoneId.systemDefault())
//                .toLocalDateTime();
//        LocalDateTime.
//        LocalDateTime endTime = createTime.plusDays(30);
        // 转换时保留时区信息
        ZonedDateTime zonedCreateTime = createDate.toInstant()
                .atZone(ZoneId.systemDefault());
        ZonedDateTime endTime = zonedCreateTime.plusDays(35);

        // 转回 Date 类型
        Date endDate = Date.from(endTime.toInstant());
        mdjfCaseMain.setDisposeEndTime(endDate);
        mdjfCaseMain.setDeptId(mdjfCaseMain.getCheckinDeptId());
        mdjfCaseMain.setUserId(mdjfCaseMain.getCheckinExperiencedSysUserId());
        return mdjfCaseMainMapper.insertMdjfCaseMain(mdjfCaseMain);
    }

    /**
     * 修改矛盾纠纷--案件主事件
     * 
     * @param mdjfCaseMain 矛盾纠纷--案件主事件
     * @return 结果
     */
    @Override
    public int updateMdjfCaseMain(MdjfCaseMain mdjfCaseMain)
    {
        mdjfCaseMain.setUpdateTime(DateUtils.getNowDate());
        return mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
    }

    /**
     * 批量删除矛盾纠纷--案件主事件 (逻辑删除) status=1
     * 
     * @param caseMainIds 需要删除的矛盾纠纷--案件主事件主键
     * @return 结果
     */
    @Override
    public int deleteMdjfCaseMainByCaseMainIds(Long[] caseMainIds)
    {
        return mdjfCaseMainMapper.batchUpdateStatus(caseMainIds);
    }

    /**
     * 批量督办矛盾纠纷--案件主事件
     *
     * @param caseMainIds
     * @return 结果
     */
    @Override
    public int supervisingIds(Long[] caseMainIds)
    {
        Long userId = SecurityUtils.getUserId();
        MdjfCaseMain mdjfCaseMain = new MdjfCaseMain();
        int count = 0;
        mdjfCaseMain.setSupervisingSysUserId(userId);
        mdjfCaseMain.setSupervisingTime(DateUtils.getNowDate());
        mdjfCaseMain.setSupervisingIs(0);
        for (int i = 0; i < caseMainIds.length; i++) {
            mdjfCaseMain.setCaseMainId(caseMainIds[i]);
            mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
            count++;
        }
        return count;
    }

    /**
     * 删除矛盾纠纷--案件主事件信息
     * 
     * @param caseMainId 矛盾纠纷--案件主事件主键
     * @return 结果
     */
    @Override
    public int deleteMdjfCaseMainByCaseMainId(Long caseMainId)
    {
        return mdjfCaseMainMapper.deleteMdjfCaseMainByCaseMainId(caseMainId);
    }

    @Override
    public int withdraw(MdjfCaseMain mdjfCaseMain) {
        mdjfCaseMain.setUpdateTime(DateUtils.getNowDate());
        return mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
    }

    @Override
    public int accept(MdjfCaseMain mdjfCaseMain) {
        mdjfCaseMain.setUpdateTime(DateUtils.getNowDate());
        mdjfCaseMain.setCheckinAcceptTime(DateUtils.getNowDate());
        return mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
    }

    /**
     *  案件处理 /办结
     * @param mdjfCaseMain
     * @return
     */
    @Override
    public int dispose(MdjfCaseMain mdjfCaseMain) {
        MdjfCaseMain mdjfCaseMain1 = mdjfCaseMainMapper.selectMdjfCaseMainByCaseMainId(mdjfCaseMain.getCaseMainId());
        if (mdjfCaseMain1 == null) {
            throw new RuntimeException("案件不存在");
        }else {
            if (mdjfCaseMain1.getDisposeStatus() == 0 || mdjfCaseMain1.getIsAccept() == 1) {
                throw new RuntimeException("案件还未受理，不能处理。");
            }
        }


        mdjfCaseMain.setUpdateTime(DateUtils.getNowDate());
        mdjfCaseMain.setDeptdisposeTime(DateUtils.getNowDate());
        if (mdjfCaseMain.getDeptdisposeReturnInfo() != null && !"".equals(mdjfCaseMain.getDeptdisposeReturnInfo())){
            // 存在回访信息，更新状态为已回访 且案件完结
            mdjfCaseMain.setDeptdisposeReturnIs(0);
            mdjfCaseMain.setDisposeStatus(3);
            mdjfCaseMain.setDeptdisposeReturnTime(DateUtils.getNowDate());
        }else {
            mdjfCaseMain.setDisposeStatus(2);
            mdjfCaseMain.setDeptdisposeReturnIs(1);
        }
        // 处理时间
        mdjfCaseMain.setDeptdisposeTime(DateUtils.getNowDate());

        // 存在诉讼参与人，更新诉讼参与人信息
        if (mdjfCaseMain.getMdjfCasePersonList() != null && mdjfCaseMain.getMdjfCasePersonList().size() > 0){
            // 删除原有的诉讼参与人
            mdjfCasePersonService.deleteMdjfCasePersonByCaseMainId(mdjfCaseMain.getCaseMainId());
            // 存在诉讼参与人，
            mdjfCaseMain.getMdjfCasePersonList().forEach(person -> {
                // 有id采用原id插入，没有遵从自增id
                mdjfCasePersonService.insertMdjfCasePerson(person);
            });
        }else {
            // 没有诉讼参与人，删除原有的诉讼参与人
            mdjfCasePersonService.deleteMdjfCasePersonByPersonId(mdjfCaseMain.getCaseMainId());
        }


        return mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
    }

    @Override
    public int disposereturn(MdjfCaseMain mdjfCaseMain) {
        if (mdjfCaseMain.getDeptdisposeReturnInfo() == null || "".equals(mdjfCaseMain.getDeptdisposeReturnInfo())){
            throw new RuntimeException("回访信息不能为空。");
        }
        mdjfCaseMain.setUpdateTime(DateUtils.getNowDate());
        mdjfCaseMain.setDeptdisposeTime(DateUtils.getNowDate());
        // 存在回访信息，更新状态为已回访 且案件完结
        mdjfCaseMain.setDeptdisposeReturnIs(0);
        mdjfCaseMain.setDisposeStatus(3);
        mdjfCaseMain.setDeptdisposeReturnTime(DateUtils.getNowDate());
        return mdjfCaseMainMapper.updateMdjfCaseMain(mdjfCaseMain);
    }


    /**
     * 构建数据  列表数据 详情数据回显数据
     * @param m
     * @return
     */
    private MdjfCaseMain buildData(MdjfCaseMain m) {
        // 分流窗口
        if(m.getDemandsSysUserId() != null && m.getDemandsSysUserId() != 0L){
            SysUser user = sysUserService.selectUserById(m.getDemandsSysUserId());
            if (user!= null){
                m.setDemandsSysUserName(user.getUserName());
            } else {
                m.setDemandsSysUserName("未知");
            }
        }
        // 诉求人-用户性别
        if(m.getDemandsSex() != null && m.getDemandsSex() != ""){
            String typeData = sysDictDataService.selectDictLabel("sys_user_sex", m.getDemandsSex());
            if(typeData != null && !"".equals(typeData)){
                m.setDemandsSexNmae(typeData);
            }else {
                m.setDemandsSexNmae("未知");
            }

        }
        // 登记信息-纠纷类型
        if(m.getCheckinDictJflxId() != null){
            String typeData = sysDictDataService.selectDictLabel("dict_jflx", m.getCheckinDictJflxId().toString());
            if(typeData != null && !"".equals(typeData)){
                m.setCheckinDictJflxName(typeData);
            }else {
                m.setCheckinDictJflxName("未知");
            }
        }

        // 登记信息-信访部门
        if(m.getCheckinDeptId() != null && m.getCheckinDeptId() != 0L){
            SysDept dept = sysDeptService.selectDeptById(m.getCheckinDeptId());
            if (dept!= null){
                m.setCheckinDeptName(dept.getDeptName());
            } else {
                m.setDemandsSysUserName("未知");
            }
        }
        // 登记信息-窗口经办人
        if(m.getCheckinExperiencedSysUserId() != null && m.getCheckinExperiencedSysUserId() != 0L){
            SysUser user = sysUserService.selectUserById(m.getCheckinExperiencedSysUserId());
            if (user!= null){
                m.setCheckinExperiencedSysUserName(user.getUserName());
            } else {
                m.setCheckinExperiencedSysUserName("未知");
            }
        }

        // 部门处理信息-部门经办人
        if(m.getDeptdisposeExperiencedSysUserId() != null && m.getDeptdisposeExperiencedSysUserId() != 0L){
            SysUser user = sysUserService.selectUserById(m.getDeptdisposeExperiencedSysUserId());
            if (user!= null){
                m.setDeptdisposeExperiencedSysUserName(user.getUserName());
            } else {
                m.setDeptdisposeExperiencedSysUserName("未知");
            }
        }

        // 登记信息-不受理的原因
        if(m.getDisposeDictNotacceptId() != null){
            String typeData = sysDictDataService.selectDictLabel("dispose_dict_notaccept_id", m.getDisposeDictNotacceptId().toString());
            if(typeData != null && !"".equals(typeData)){
                m.setDisposeDictNotacceptName(typeData);
            }else {
                m.setDisposeDictNotacceptName("未知");
            }
        }

        // 督办人
        if(m.getSupervisingSysUserId() != null && m.getSupervisingSysUserId() != 0L){
            SysUser user = sysUserService.selectUserById(m.getSupervisingSysUserId());
            if (user!= null){
                m.setSupervisingSysUserName(user.getUserName());
            } else {
                m.setSupervisingSysUserName("未知");
            }
        }

        // 高唐区县
        if(m.getCheckinTownshipId() != null && m.getCheckinTownshipId() != 0L){
            String typeData = sysDictDataService.selectDictLabel("checkin_township", m.getCheckinTownshipId().toString());
            if(typeData != null && !"".equals(typeData)){
                m.setCheckinTownshipName(typeData);
            }else {
                m.setCheckinTownshipName("未知");
            }
        }


        // 查询事件相关人员数据
        MdjfCasePerson casePerson = new MdjfCasePerson();
        casePerson.setCaseMainId(m.getCaseMainId());
        List<MdjfCasePerson> casePersonList = mdjfCasePersonService.selectMdjfCasePersonList(casePerson);
        m.setMdjfCasePersonList(casePersonList);

        MdjfCaseBczl mdjfCaseBczl = new MdjfCaseBczl();
        mdjfCaseBczl.setCaseMainId(m.getCaseMainId());
        m.setMdjfCaseBczlList(mdjfCaseBczlService.selectMdjfCaseBczlList(mdjfCaseBczl));

        return m;
    }

    public YearStatResult getYearStat(Integer targetYear) {
        // 1. 执行数据库查询
        List<MonthDeptStat> rawData = mdjfCaseMainMapper.selectYearStat(targetYear);

        // 2. 构建包含12个月的结构化数据
        YearStatResult result = new YearStatResult();
        result.setYear(targetYear);
        result.setMonthlyData(IntStream.rangeClosed(1, 12)
                .mapToObj(month -> {
                    YearStatResult.MonthStat monthStat = new YearStatResult.MonthStat();
                    monthStat.setMonth(month);


                    // 过滤并排序当月数据
                    List<YearStatResult.DeptStat> deptStats = rawData.stream()
                            .filter(d -> month == d.getStatMonth())
                            .sorted(Comparator.comparingInt(MonthDeptStat::getCaseCount).reversed())
                            .map(d -> {
                                YearStatResult.DeptStat ds = new YearStatResult.DeptStat();
                                ds.setDeptName(d.getDeptName());
                                ds.setCaseCount(d.getCaseCount());
                                monthStat.setMonthTotal(d.getMonthlyTotal());
                                return ds;
                            })
                            .collect(Collectors.toList());

                    // 处理无数据情况
                    if (deptStats.isEmpty()) {
                        deptStats.add(createEmptyDeptStat());
                    }
                    monthStat.setDeptStats(deptStats);
                    return monthStat;
                })
                .collect(Collectors.toList()));
        return result;
    }


    @Override
    public DayStatResult getDayDeptStat(String day) {
        DayStatResult result = new DayStatResult();
        result.setDay(day);
        List<DayDeptStat> dayDeptList = mdjfCaseMainMapper.getDayDeptStat(day);
        result.setDayDeptList(dayDeptList);
        if (dayDeptList == null || dayDeptList.size() == 0) {
            result.setTotalCount(0);
        }else {
            result.setTotalCount(dayDeptList.get(0).getTotalCount());

        }


        result.setDayStatContent("");

        return result;
    }

    @Override
    public List<CaseHandlingResult> getCaseHandling(String day) {
        return mdjfCaseMainMapper.getCaseHandling(day);
    }

    /**
     * 最近7天数据趋势
     * @return
     */
    @Override
    public ReRecentTrend recentTrend() {
        ReRecentTrend result = new ReRecentTrend();
        // 1. 查询最近7天的数据
        result.setCaseMainTrend(mdjfCaseMainMapper.getRecentTrend(1));
        result.setCaseDisposeTrend(mdjfCaseMainMapper.getRecentTrend(2));
        result.setCaseWarningTrend(mdjfCaseMainMapper.getRecentTrend(3));
        result.setCaseSuperviseTrend(mdjfCaseMainMapper.getRecentTrend(4));
        return result;
    }

    @Override
    public HashMap<String, String> handleAnalytics() {
        HashMap<String, String> map = new HashMap<>();
//        map.put("CaseMainBl", "100.00");
        // 1. 查询案件总数
        Integer mainCount = mdjfCaseMainMapper.handleAnalytics("");
        // 2. 查询处理案件数 包含待办理、完结
        Integer disposeCount = mdjfCaseMainMapper.handleAnalytics("2");
        // 3.完结案件数
        Integer overCount = mdjfCaseMainMapper.handleAnalytics("3");
        disposeCount = disposeCount + overCount;
        // 4.未受理案件数
        Integer noDisposeCount = mdjfCaseMainMapper.handleAnalytics("1");

        // 5. 查询案件总数占比
        String mainPercent = String.format("%.2f", ((double) mainCount / mainCount) * 100);
        // 6. 查询处理案件数 包含待办理、完结占比
        String disposePercent = String.format("%.2f", ((double) disposeCount / mainCount) * 100);
        // 7. 完结案件数占比
        String overPercent = String.format("%.2f", ((double) overCount / mainCount) * 100);
        // 8. 未受理案件数占比
        String noDisposePercent = String.format("%.2f", ((double) noDisposeCount / mainCount)* 100);
        // 9. 构建返回数据
        map.put("CaseMainCount", mainCount.toString());
        map.put("CaseMainPercent", mainPercent);
        map.put("CaseDisposeCount", disposeCount.toString());
        map.put("CaseDisposePercent", disposePercent);
        map.put("overCount", overCount.toString());
        map.put("overPercent", overPercent);
        map.put("noDisposeCount", noDisposeCount.toString());
        map.put("noDisposePercent", noDisposePercent);
        return map;
    }

    @Override
    public CasesGrowResult casesGrow() {
        CasesGrowResult casesGrowResult = new CasesGrowResult();
        // 1. 查询最近7天的数据
        casesGrowResult.setDisposeStatus0(mdjfCaseMainMapper.CasesGrowResult(0));
        casesGrowResult.setDisposeStatus1(mdjfCaseMainMapper.CasesGrowResult(1));
        casesGrowResult.setDisposeStatus2(mdjfCaseMainMapper.CasesGrowResult(2));
        casesGrowResult.setDisposeStatus3(mdjfCaseMainMapper.CasesGrowResult(3));

        // 2. 查询案件各状态数量及总数
        MdjfCaseMain mdjfCaseMain = new MdjfCaseMain();

        mdjfCaseMain.setStatus(0);

        List<ReTrend> totalCount = new ArrayList<>();
        ReTrend reTrend = new ReTrend();
        reTrend.setDailyCount(String.valueOf(mdjfCaseMainMapper.selectMdjfCaseMainListNoAuth(mdjfCaseMain).size()));
        reTrend.setStatDate("总数");
        totalCount.add(reTrend);

        mdjfCaseMain.setDisposeStatus(0);
        ReTrend reTrend0 = new ReTrend();
        reTrend0.setDailyCount(String.valueOf(mdjfCaseMainMapper.selectMdjfCaseMainListNoAuth(mdjfCaseMain).size()));
        reTrend0.setStatDate("待受理");
        totalCount.add(reTrend0);

        mdjfCaseMain.setDisposeStatus(1);
        ReTrend reTrend1 = new ReTrend();
        reTrend1.setDailyCount(String.valueOf(mdjfCaseMainMapper.selectMdjfCaseMainListNoAuth(mdjfCaseMain).size()));
        reTrend1.setStatDate("待处理");
        totalCount.add(reTrend1);

        mdjfCaseMain.setDisposeStatus(2);
        ReTrend reTrend2 = new ReTrend();
        reTrend2.setDailyCount(String.valueOf(mdjfCaseMainMapper.selectMdjfCaseMainListNoAuth(mdjfCaseMain).size()));
        reTrend2.setStatDate("处理中");
        totalCount.add(reTrend2);

        mdjfCaseMain.setDisposeStatus(3);
        ReTrend reTrend3 = new ReTrend();
        reTrend3.setDailyCount(String.valueOf(mdjfCaseMainMapper.selectMdjfCaseMainListNoAuth(mdjfCaseMain).size()));
        reTrend3.setStatDate("已办结");
        totalCount.add(reTrend3);
        casesGrowResult.setTotalCount(totalCount);
        return casesGrowResult;
    }

    @Override
    public CasesGrowResult casesDispose() {
        CasesGrowResult casesGrowResult = new CasesGrowResult();
        // 1. 查询最近7天的数据
        casesGrowResult.setDisposeStatus0(mdjfCaseMainMapper.CasesGrowResult(null));

        casesGrowResult.setDisposeStatus1(mdjfCaseMainMapper.CasesGrowResult(3));
        return casesGrowResult;
    }

    @Override
    public List<CasesRegionResult> casesRegion() {

        return mdjfCaseMainMapper.CasesRegion();
    }


    private YearStatResult.DeptStat createEmptyDeptStat() {
        YearStatResult.DeptStat ds = new YearStatResult.DeptStat();
        ds.setDeptName("无数据");
        ds.setCaseCount(0);
        return ds;
    }
}
